﻿using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Reflection;

using Kuiper.Core;
using Kuiper.WinUI.EventHandlers;

namespace Kuiper.WinUI;

public partial class KpMasterDetailFormBase : MaterialForm
{
	public event GridViewItemActivedHandler ItemActived = null;

	public required Type MasterListObjectType { get; set; }

	public KpMasterDetailFormBase()
	{
		InitializeComponent();
	}

	protected override void OnLoad(EventArgs e)
	{
		base.OnLoad(e);

		this.Text = MasterListObjectType.Name;

		CreateGridView();

		BindingGridView();

		BuildFormSlots();
	}

	protected override void OnResizeEnd(EventArgs e)
	{
		base.OnResizeEnd(e);

		KpDetailTabPage.ResumeLayout(true);
	}

	private void CreateGridView()
	{
		KpListMasterDataGridView.Columns.Clear();
		KpListMasterDataGridView.AutoGenerateColumns = false;
		KpListMasterDataGridView.ReadOnly = true;

		// Order the properties by key, required
		var masterProperties = this.MasterListObjectType.GetProperties().Select(propertyInfo =>
		{
			var keyAttribute = propertyInfo.GetCustomAttribute<DevExpress.Xpo.KeyAttribute>();
			var requiredAttribute = propertyInfo.GetCustomAttribute<RequiredAttribute>();

			return new
			{
				PropertyInfo = propertyInfo,
				IsKeyProperty = (keyAttribute != null),
				IsRequiredProperty = (requiredAttribute != null)
			};
		})
		.OrderByDescending(x => x.IsKeyProperty)
		.ThenByDescending(x => x.IsRequiredProperty)
		.Select(x => x.PropertyInfo).ToList();

		// Add the collumns to grid view
		foreach (var propertyInfo in masterProperties)
		{
			var browsableAttribute = propertyInfo.GetCustomAttribute<BrowsableAttribute>();

			if (browsableAttribute?.Browsable != false)
			{
				KpListMasterDataGridView.Columns.Add(new DataGridViewTextBoxColumn()
				{
					Name = $"{MasterListObjectType.Name}-{propertyInfo.Name}",
					HeaderText = propertyInfo.Name,
					DataPropertyName = propertyInfo.Name,
					ReadOnly = true,
				});
			}
		}

		// Set the last column fill width mode
		var lastColumn = KpListMasterDataGridView.Columns.GetLastColumn(DataGridViewElementStates.Visible, DataGridViewElementStates.None);
		if (lastColumn != null)
		{
			lastColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
		}
	}

	private void BindingGridView()
	{
		var objectList = KPSession.GetList(MasterListObjectType);
		KpListMasterDataGridView.DataSource = objectList;
	}

	private void BuildFormSlots()
	{
		FormBuilder.Create(this.MasterListObjectType, KpDetailTabPage);
	}

	private void KpListMasterDataGridView_RowEnter(object sender, DataGridViewCellEventArgs e)
	{
		if (ItemActived != null)
		{
			ItemActived(sender, e);
		}
	}
}
